<?php
/**
 * Zeed Platform Project
 * Based on Zeed Framework & Zend Framework.
 *
 * LICENSE
 * http://www.zeed.com.cn/license/
 *
 * @category Zeed
 * @package Zeed_ChangeMe
 * @subpackage ChangeMe
 * @copyright Copyright (c) 2010 Zeed Technologies PRC Inc. (http://www.zeed.com.cn)
 * @author Zeed Team (http://blog.zeed.com.cn)
 * @since 2010-12-6
 * @version SVN: $Id$
 */

class ContentController extends AttachmentAdminAbstract
{
    protected $perpage = 20;
    
    /**
     * 资源列表
     */
    public function index()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $ordername = $this->input->get('ordername', null);
        $orderby = $this->input->get('orderby', null);
        $page = (int) $this->input->get('pageIndex', 0);
        $perpage = (int) $this->input->get('pageSize', $this->perpage);
        $key = trim($this->input->get('key'));
        $time_start = $this->input->get('time_start');
        $time_end = $this->input->get('time_end');
        $resource_type = $this->input->get('resource_type');
        
        /* ajax 加载数据 */
        if ($this->input->isAJAX()) {
            $offset = $page * $perpage;
            $page = $page + 1;
            
            /* 处理时间排序 */
            $time_se = array($time_start, $time_end);
            asort($time_se);
            $time_se = array_values($time_se);
            $time_start = $time_se[0];
            $time_end = $time_se[1];
            
            /* 组织查询条件 */
            $where['status'] = 1;
            if ($time_start && $time_end) {
                $where['$and'] = [
                        ['ctime'=>
                                ['$gte' => strtotime($time_start) * 1000] // new MongoDate()
                        ],
                        ['ctime'=>
                                ['$lte' =>  (strtotime($time_end) + 24 * 3600 - 1) * 1000]
                        ]
                ];
            } else {
                if ($time_start) {
                    $startime = strtotime($time_start) * 1000; // new MongoDate(strtotime($time_start));
                    $where['ctime'] = ['$gte' => $startime];
                }
                
                if ($time_end) {
                    $endtime = (strtotime($time_end) + 24 * 3600 - 1) * 1000;
                    $where['ctime'] = ['$lte' => $endtime];
                }
            }
            if ($resource_type) {
                $where['mediatype'] = $resource_type;
            }
            if ($key) {
                $where['$or'] = array(
                        array('title' => new MongoRegex("/$key/i"))
                );
            }
            $order = array('ctime' => 'DESC');
            
            /* 执行查询 */
            $content = Attachment_Model_Content::instance()->fetchByWhere($where, $order, $perpage, $offset);
            $data['count'] = Attachment_Model_Content::instance()->getCount($where);
            
            /* 处理其他一些信息 */
            if (! empty($content)) {
                foreach ($content as $k => &$v) {
                    /* 查询隶属资料卡 */
                    $image_belongto_type = 'image';
                    if ($v['pid']) {
                        $belongto_id = $v['pid'];
                        if ($v['mediatype'] == 'image') {
                            $parent_attachment_info = Attachment_Model_Content::instance()->fetchByPK($belongto_id);
                            if ($parent_attachment_info[0]['mediatype'] == 'video') {
                                $image_belongto_type = 'video';
                            }
                        }
                    } else {
                        $belongto_id = $v['_id'];
                    }
                    
                    $v['belongto_card'] = '';
                    if ($v['mediatype'] == 'image') {
                        if ($image_belongto_type == 'video') {
                            $where_card = array('attachments_video' => new MongoRegex("/" . $belongto_id . "/i"));
                        } else {
                            $where_card = array('attachments_img' => new MongoRegex("/" . $belongto_id . "/i"));
                        }
                    } elseif ($v['mediatype'] == 'audio') {
                        $where_card = array('attachments_audio' => new MongoRegex("/" . $belongto_id . "/i"));
                    } elseif ($v['mediatype'] == 'video') {
                        $where_card = array('attachments_video' => new MongoRegex("/" . $belongto_id . "/i"));
                    }
                    $card_info = Archive_Model_Card::instance()->fetchByWhere($where_card);
                    if (! empty($card_info)) {
                        $v['belongto_card'] = $card_info[0]['title'];
                        if (mb_strlen($v['belongto_card']) > 16) {
                            $v['belongto_card'] = mb_substr($v['belongto_card'], 0, 16);
                        }
                    }
                    
                    /* 查询隶属案件 */
                    $v['belongto_archive'] = '';
                    if (! empty($card_info)) {
                        $archive_info = Archive_Model_Content::instance()->fetchByFV('sn', $card_info[0]['sn']);
                        if (! empty($archive_info)) {
                            $v['belongto_archive'] = $archive_info[0]['title'];
                            if (mb_strlen($v['belongto_archive']) > 16) {
                                $v['belongto_archive'] = mb_substr($v['belongto_archive'], 0, 16);
                            }
                        }
                    }
                    
                    /* 处理来源 */
                    $v['source'] = '上传';
                    if ($v['pid']) {
                        if ($v['mediatype'] == 'video') {
                            $v['source'] = '视频截短';
                        } elseif ($v['mediatype'] == 'audio') {
                            $extra = json_decode($v['extra'], true);
                            if ($extra['type'] == 'clip') {
                                $v['source'] = '音频截短';
                            } else {
                                $v['source'] = '音频处理';
                            }
                        } elseif ($v['mediatype'] == 'image') {
                            $v['source'] = '图片处理';
                        }
                    }
                    
                    /* 处理时间 */
                    if (strlen($v['ctime']) == 13) {
                        $v['ctime'] = date(DATETIME_FORMAT, $v['ctime'] / 1000);
                    } else {
                        $v['ctime'] = date(DATETIME_FORMAT, $v['ctime']);
                    }
                    
                    /* 处理地址 */
                    $v['filepath'] = Support_Image_Url::getImageUrl($v['filepath']);
                }
            }
            
            $data['content'] = $content ? $content : array();
        }
        
        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'content.index');
        return parent::multipleResult(self::RS_SUCCESS);
    }
    
    /**
     * 编辑
     */
    public function edit ()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        if ($this->input->isPOST()) {
            $this->editSave();
            return self::RS_SUCCESS;
        }
        
        /* 接收参数 */
        $_id = $this->input->query('_id');
        
        /* 检查内容是否存在 */
        $content = Attachment_Model_Content::instance()->fetchByPK($_id);
        if (empty($content)) {
            throw new Zeed_Exception('资源内容不存在');
        }
        
        $data['content'] = $content[0];
        
        $this->setData('data', $data);
        $this->addResult(self::RS_SUCCESS, 'php', 'content.edit');
        return parent::multipleResult(self::RS_SUCCESS);
    }
    
    /**
     * 编辑 - 保存
     */
    public function editSave ()
    {
        try {
            /* 接收参数 */
            $_id = $this->input->post('_id');
            $title = trim($this->input->post('title'));
            
            /* 数据验证 */
            if (! $title) {
                throw new Zeed_Exception('请输入资源名称');
            }
            if (! $_id) {
                throw new Zeed_Exception('缺少参数或参数错误');
            }
            
            /* 更新数据 */
            $set_update = array(
                    'title' => $title,
                    'mtime' => Util_Timer::getMicrotime()
            );
            Attachment_Model_Content::instance()->updateForEntity($set_update, $_id);
            
            /* @todo 记录日志 */
        } catch (Zeed_Exception $e) {
            $this->setStatus(1);
            $this->setError('编辑失败 : ' . $e->getMessage());
        }
        
        return false;
    }
    
    /**
     * 删除资源
     */
    public function delete()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $_id = $this->input->query('_id');
        
        try {
            /* 检查请求方式 */
            if (! $this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }
            
            /* 检查请求参数 */
            if (! $_id) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }
            
            /* 查询资源是否存在 */
            $content_info = Attachment_Model_Content::instance()->fetchByPK($_id);
            if (empty($content_info)) {
                throw new Zeed_Exception('查无此资源');
            }
            $content_info = $content_info[0];
            
            /* 查询资源是否正在被使用 */
            $file_is_using = false;
            $attachments = Attachment_Model_Content::instance()->fetchByFV('hashcode', $content_info['hashcode']);
            if (! empty($attachments)) {
                foreach ($attachments as $k => $v) {
                    if ($v['_id'] == $_id) {
                        continue;
                    }
                    
                    $where_card['$or'] = array(
                            array('attachments_img' => new MongoRegex("/" . $v['_id'] . "/i")),
                            array('attachments_audio' => new MongoRegex("/" . $v['_id'] . "/i")),
                            array('attachments_video' => new MongoRegex("/" . $v['_id'] . "/i"))
                    );
                    $count_card = Archive_Model_Card::instance()->getCount($where_card);
                    if ($count_card > 0) {
                        $file_is_using = true;
                        break;
                    }
                }
            }
            
            /* 删除对应物理文件 */
            if ($file_is_using == true) {
                @unlink(ZEED_PATH_UPLOAD . $content_info['filepath']);
            }
            
            /* 删除资源记录 */
            Attachment_Model_Content::instance()->deleteByPK($_id);
            
            /* @todo 记录日志 */
            
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('删除失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 移动资源
     */
    public function move()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $_id = $this->input->query('a_id');
        $fid = (int) $this->input->query('fid');
        $userid = (int) $this->input->query('userid', $this->_userid_fs);
        
        try {
            /* 检查请求方式 */
            if (! $this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }
            
            /* 检查请求参数 */
            if (! $_id || ! $fid) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }
            
            /* 执行移动 */
            $params_move = array(
                    'userid' => $userid,
                    'attachments' => $_id,
                    'target_folder_fid' => $fid,
                    'is_force' => 1
            );
            $result = Attachment_Move::run($params_move);
            if ($result['status'] != 0) {
                throw new Zeed_Exception($result['msg'], $result['status']);
            }
            
            /* @todo 记录日志 */
            
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('移动失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 根据任务 ID 查询附件信息 - 支持批量
     */
    public function getAttachmentsByOrderIds()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $order_id = $this->input->query('order_id');
        
        try {
            /* 检查请求方式 */
            if (! $this->input->isAJAX()) {
//                 throw new Zeed_Exception('请求方式错误');
            }
            
            /* 检查请求参数 */
            if (! $order_id) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }
            
            /* 组织查询条件 */
            $where = array('order_id' => array('$in' => explode(',', $order_id)));
            
            /* 执行查询 */
            $attachment_temp = Attachment_Model_Content_Temp::instance()->fetchByWhere($where);
            
            /* 组织返回数据 */
            $attachments = array();
            if (! empty($attachment_temp)) {
                $config_storage = Zeed_Storage::instance()->getConfig();
                foreach ($attachment_temp as $k => $v) {
                    /* 处理扩展信息 */
                    $extra = ! empty($v['extra']) ? json_decode($v['extra'], true) : array();
                    
                    /* 处理封面图 */
                    if (isset($extra['cover'])) {
                        $extra['cover'] = Support_Image_Url::getImageUrl($extra['cover']);
                    }
                    
                    $attachments[$v['order_id']] = array(
                            '_id' => $v['_id'],
                            'title' => $v['title'],
                            'mediatype' => $v['mediatype'],
                            'image_width' => $v['image_width'],
                            'image_height' => $v['image_height'],
                            'filepath' => $v['filepath'],
                            'url' => Support_Image_Url::getImageUrl($v['filepath']),
                            'filesize' => $v['filesize'],
                            'filesize_format' => Util_File::formatFilesize($v['filesize']),
                            'hashcode' => $v['hashcode'],
                            'order_id' => $v['order_id'],
                            'extra' => $extra,
                            'status' => $v['status'],
                            'ctime' => Util_Timer::formatMicrotime($v['ctime'], 'Y-m-d H:i:s')
                    );
                }
            }
            
            $data['attachments'] = $attachments;
            $this->setData('data', $data);
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('查询失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 产生缩略图(JPEG格式)地址或文件类型图标地址 注意: 缩略图的扩展名可能不代表其真实的MIMEType
     *
     * @param boolean $filepath
     * @param string $mimetype 文件的MIMEType类型
     * @param string $thumbScheme 指定的已配置缩略图方案
     * @param string $urlPrefix 上传目录可访问地址
     * @return string 返回缩略图地址
     */
    protected function _generateThumbnailsUrl($filepath, $mimetype, $thumbScheme, $urlPrefix = null)
    {
        if (substr($mimetype, 0, 6) != 'image/') {
            $configIconsAttachment = Zeed_Config::loadGroup('icon.attachment');
            if (!isset($configIconsAttachment['list'][$mimetype])) {
                $thumbUrl = $configIconsAttachment['default'];
            } else {
                $thumbUrl = $configIconsAttachment['list'][$mimetype];
            }
            return $thumbUrl;
        }
        
        $thumbUrl = '';
        $suffix = substr($filepath, strrpos($filepath, '.'));
        $thumbUrl = str_replace($suffix, '_' . $thumbScheme . $suffix, $filepath);
        
        if (is_null($urlPrefix)) {
            $config = Zeed_Storage::instance()->getConfig();
            $thumbUrl = $config['url_thumb_mng_prefix'] . $thumbUrl;
        } else {
            $thumbUrl = $urlPrefix . $thumbUrl;
        }
        
        return $thumbUrl;
    }
}

// End ^ LF ^ encoding
